const dotenv = require('dotenv');
dotenv.config(); // 加载环境变量
const qiniu = require('qiniu')
const path = require('path')
const fs = require('fs')
const crypto = require('crypto');
const { getUploadToken } = require('../config/qiniu')

// 文件类型映射文件夹
const typeFolders = {
    'image': 'photos/',
    'video': 'videos/',
    'audio': 'voices/'
}

// 上传到七牛云
// uploadToQiniu 函数强化版
async function uploadToQiniu(file) {
    // 原子性校验
    const stat = fs.statSync(file.path);
    if (stat.size <= 0) throw new Error('空文件禁止上传');

    // 强化类型映射
    const type = file.mimetype.split('/')[0];
    if (!typeFolders[type]) throw new Error('非法文件类型');
    
    // 生成带目录结构的文件名
    const folder = typeFolders[type];
    const ext = path.extname(file.originalname);
    const filename = `${folder}${Date.now()}_${crypto.randomBytes(4).toString('hex')}${ext}`;

    // 带重试机制的上传
    let retry = 3;
    while (retry--) {
        try {
            return await executeUpload(filename, file.path);
        } catch (err) {
            if (err.code === 'ECONNRESET') continue;
            throw err;
        }
    }
}

function executeUpload(key, filePath) {
    return new Promise((resolve, reject) => {
      const formUploader = new qiniu.form_up.FormUploader(
        new qiniu.conf.Config({
          retry: 0,
          useHttpsDomain: true // 确保开启HTTPS
        })
      );
  
      formUploader.putFile(
        getUploadToken(key),
        key,
        filePath,
        new qiniu.form_up.PutExtra(),
        // 修正参数接收顺序 (err, respBody, respInfo)
        (err, respBody, respInfo) => { // ✅ 关键修复点
          if (err) return reject(err);
          
          // 正确读取状态码
          if (respInfo.statusCode !== 200) {
            console.error('七牛异常响应详情:', {
              statusCode: respInfo.statusCode,
              headers: respInfo.headers,
              body: respBody
            });
            return reject(new Error(`七牛云接口异常: ${respInfo.statusCode}`));
          }
  
          // 强制使用HTTPS链接
          resolve({
            url: `http://${process.env.QINIU_DOMAIN}/${respBody.key}`, // 修复HTTP为HTTPS
            hash: respBody.hash
          });
        }
      );
    });
  }


module.exports = { uploadToQiniu }